var cameraHeight = 1000; //缺省高度
var cameraPitch = 330; //缺省俯仰角
var globleInterval = null; //全局事件触发器
var globleFlyIndex = 0;

/**
 * 初始化事件绑定
 */
function addEvent(){
    var intervalValue = 2;
    var intervalTime = 30;
    var points = [
                [107.01722208477538,39.43873080585334],
                [107.022410687048,39.51070150694491],
                [107.01495108356599,39.576563342901714],
                [107.0021200512855,39.65512925862155],
                [106.9595781265832,39.68479518763417]
            ];
    var vPoint = [];
    var terrainPoints = [];
    var viewerPoints = [];
    var allPoints = [];
    for (var i = 0 ; i < points.length ; i ++){
        terrainPoints.push(Cesium.Cartographic.fromDegrees(points[i][0], points[i][1]));
        viewerPoints.push(Cesium.Cartesian3.fromDegrees(points[i][0], points[i][1]));
        vPoint.push({
            x: points[i][0],
            y: points[i][1],
            z: 0
        });
    }
    $("#showPath").click(function(){
        viewer.entities.add({
            polyline: {
                clampToGround: true,
                positions: viewerPoints,
                material: Cesium.Color.YELLOW.withAlpha(1),
                width: 5
            }
        });
    });
    $("#deletePath").click(function(){
        viewer.entities.removeAll();
    });
    $("#flyPath").click(function(){
        allPoints = [];
        var angleList = [];
        for (var i = 0 ; i < vPoint.length ; i ++){
            if(vPoint[i + 1]){
                //var angle = courseAngle(vPoint[i + 1].x,vPoint[i + 1].y,vPoint[i].x,vPoint[i].y);
                var angle = CalulateXYAnagle(vPoint[i].x,vPoint[i].y,vPoint[i + 1].x,vPoint[i + 1].y);
                var array = getIntervalPoint([vPoint[i], vPoint[i + 1]]);
                allPoints = allPoints.concat(array);
                angleList.push({
                    index: allPoints.length,
                    angle: angle
                });
            }
        }
        //TODO 计算点的高程值
        var promise = Cesium.sampleTerrain(viewer.terrainProvider, 15, allPoints);
        Cesium.when(promise, function(updatedPositions) {
            allPoints = updatedPositions;
            viewerCamera(allPoints,angleList);
        });
    });
    $("#pausePath").click(function(){
        window.clearInterval(globleInterval);
    });
    $("#exitPath").click(function(){
        globleFlyIndex = 0;
        window.clearInterval(globleInterval);
    });

    /**
     *  执行三维飞行
     * @param allPoint
     * @param heights
     */
    function viewerCamera(allPoint,angleList){
        var pitch = $(".flyPitch").val() || cameraPitch;
        if(pitch){
            pitch = parseFloat(pitch);
        }
        window.clearInterval(globleInterval);
        cameraHeight = parseFloat($(".flyHeight").val());
        globleInterval = setInterval(function(){
            if(!allPoint[globleFlyIndex]){
                window.clearInterval(globleInterval);
                return;
            }
            var angle = 0;
            for(var j = 0 ; j < angleList.length ; j ++){
                if(globleFlyIndex < angleList[j].index){
                    angle = angleList[j].angle;
                    break;
                }
            }
            var longitude = Cesium.Math.toDegrees(allPoint[globleFlyIndex].longitude);
            var latitude = Cesium.Math.toDegrees(allPoint[globleFlyIndex].latitude);
            var height = allPoint[globleFlyIndex].height + cameraHeight;
            viewer.camera.setView({
                destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, height),
                orientation: {
                    heading: Cesium.Math.toRadians(angle),
                    pitch: Cesium.Math.toRadians(pitch),
                    roll: 0
                }
            });
            globleFlyIndex ++;
        },intervalTime);
    }

    /**
     * 将两点以缺省的距离进行分割，返回多个point
     * @param positions
     * @returns {[]}
     */
    function getIntervalPoint(positions){
        var returnPoints = [];
        var distance = disTance(positions);
        var num = Math.ceil(distance / intervalValue);
        var x1 = positions[0].x;
        var y1 = positions[0].y;
        var x2 = positions[1].x;
        var y2 = positions[1].y;
        for (var i = 0 ; i < num ; i ++){
            let x = (x2 - x1) * ((i + 1) *  intervalValue) / distance + x1;
            let y = (y2 - y1) * ((i + 1) *  intervalValue) / distance + y1;
            returnPoints.push(Cesium.Cartographic.fromDegrees(x, y));
        }
        return returnPoints;
    }

    /**
     * 计算两点之间的距离
     * @param positions
     * @returns {number}
     */
    function disTance(positions){
        var distance = 0;
        for (var i = 0; i < positions.length - 1; i++) {
            var point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
            var point2cartographic = Cesium.Cartographic.fromCartesian(positions[i+1]);
            var geodesic = new Cesium.EllipsoidGeodesic();
            geodesic.setEndPoints(point1cartographic, point2cartographic);
            var s = geodesic.surfaceDistance;
            s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
            //s = Math.abs(point2cartographic.height - point1cartographic.height);
            distance = distance + s;
        }
        return parseFloat(distance.toFixed(3));
    }

    /**
     * 计算a点和b点的角度（偏行角）
     * @param startx a点经度
     * @param starty a点纬度
     * @param endx b点经度
     * @param endy b点纬度
     * @returns  angle 角度
     */
    function CalulateXYAnagle(startx, starty, endx, endy){
        //var tan = Math.atan(Math.abs((endy - starty) / (endx - startx))) * 180 / Math.PI;
        var angle = Math.atan2((endx - startx), (endy - starty)) * 180 / Math.PI;
        if (angle < 0) {
            return (360 + angle);
        } else {
            return (angle);
        }
    }
}
